package com.gk.study.controller;

import com.gk.study.common.APIResponse;
import com.gk.study.common.ResponeCode;
import com.gk.study.entity.Admin;
import com.gk.study.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public APIResponse login(@RequestBody Map<String, String> loginData) {
        try {
            String username = loginData.get("username");
            String password = loginData.get("password");
            
            if (username == null || password == null) {
                return new APIResponse<>(ResponeCode.FAIL, "用户名和密码不能为空");
            }

            // 检查管理员用户
            Admin admin = adminService.getAdminByUserName(username);
            if (admin == null) {
                return new APIResponse<>(ResponeCode.FAIL, "管理员不存在");
            }

            // 检查密码
            if (!password.equals(admin.getPassword())) {
                return new APIResponse<>(ResponeCode.FAIL, "密码错误");
            }

            // 检查状态
            if (admin.getStatus() == null || admin.getStatus() != 1) {
                return new APIResponse<>(ResponeCode.FAIL, "管理员账号已被禁用");
            }

            // 登录成功，返回管理员信息（不包含密码）
            Map<String, Object> adminInfo = new HashMap<>();
            adminInfo.put("id", admin.getId());
            adminInfo.put("username", admin.getUsername());
            adminInfo.put("nickname", admin.getNickname());
            adminInfo.put("role", "admin");
            adminInfo.put("avatar", admin.getAvatar());
            // 生成一个简单的token（实际项目中应该使用JWT等）
            String token = "admin_token_" + admin.getId() + "_" + System.currentTimeMillis();
            adminInfo.put("token", token);
            
            // 更新管理员的token到数据库
            admin.setToken(token);
            adminService.updateAdmin(admin);

            return new APIResponse<>(ResponeCode.SUCCESS, adminInfo);
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.INTERNAL_SERVER_ERROR, "登录失败: " + e.getMessage());
        }
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public APIResponse test() {
        return new APIResponse<>(ResponeCode.SUCCESS, "AdminController is working!");
    }
} 